<!--
 * @Description:新闻详情
-->
<template>
  <el-row>
    <el-col :span="18" :offset="1">
      <div>
        <h2>{{ detail.title }}</h2>
        <div class="time">
          {{ newsTime(detail.editTime) }}
        </div>
        <el-divider>
          <el-icon><star-filled /></el-icon>
        </el-divider>
        <div v-html="detail.content"></div>
      </div>
    </el-col>
    <el-col :span="4" :offset="1" :pull="1">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最近新闻</span>
          </div>
        </template>
        <div v-for="item in topNews" :key="item._id" class="item" @click="handleDetail(item._id)">
          <span>{{ item.title }}</span>
          <div class="bottom">
            <time class="time">{{ newsTime(item.editTime) }}</time>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import axios from 'axios'
import { onBeforeUnmount, onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { dayjs } from 'element-plus'
import { StarFilled } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const detail = ref({})
const topNews = ref([])
const getDetail = async () => {
  const res = await axios.get('/webApi/news/list/' + route.params.id)
  if (res.data.code === 200) {
    detail.value = res.data.data[0]
  }
}
// 时间处理
const newsTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
// 详情页
const handleDetail = (id) => {
  router.push(`/new_detail/${id}`)
}
// 监听ID变化
const stop= watchEffect(async () => {
  if(!route.params.id) return //详情跳转详情后再从其他页面返回会出现undefined
  getDetail()
  const res = await axios.get('/webApi/news/topList?limit=3')
  topNews.value = res.data.data
})
// 组件实例被卸载之前调用 清除
onBeforeUnmount(() => {
  stop()
})
</script>

<style lang="scss" scoped>
.time {
  color: #999;
  cursor: pointer;
}
.card-header + span {
  font-size: 16px;
  font-weight: bold;
}
.item:not(:last-child) {
  margin-bottom: 10px;
}
</style>
